I want to get the name of the two <p>
elements in my html file using id after the button is clicked. but in my code, when I clicked the button, i it only outputs "print". How can I do this?
This is my HTML code:
<p id="name" name="print">hey</p>
<p id="name" name="this">hey</p>
<button id="btn11">test11</button>
This is my javascript code:
$("#btn11").click(function(){
alert($("#name").attr("name"));
});
I want to get the name of the two <p>
elements in my html file using id after the button is clicked. but in my code, when I clicked the button, i it only outputs "print". How can I do this?
This is my HTML code:
<p id="name" name="print">hey</p>
<p id="name" name="this">hey</p>
<button id="btn11">test11</button>
This is my javascript code:
$("#btn11").click(function(){
alert($("#name").attr("name"));
});
Share
Improve this question
edited Aug 3, 2015 at 11:18
Jamiec
136k15 gold badges141 silver badges199 bronze badges
asked Aug 3, 2015 at 11:15
Jemuel ElimancoJemuel Elimanco
5562 gold badges6 silver badges20 bronze badges
2
- 3 Id be unique in HTML – Sudharsan S Commented Aug 3, 2015 at 11:16
-
7
Use
class
instead ofid
– Sapikelio Commented Aug 3, 2015 at 11:16
6 Answers
Reset to default 4use class instead of ID and
<p class= "name" name = "print">hey</p>
<p class= "name" name = "this">hey/p>
<button id="btn11">test11</button>
$("#btn11").click(function(){
$('.name').each(function () {
alert( $(this).attr('name'));
});
});
Id should be unique in HTML. Instead of id use class like this
Html:
<p class="name" name="print">hey</p>
<p class="name" name="this">hey</p>
<button id="btn11">test11</button>
jquery:
$("#btn11").click(function(){
var getName = $(".name").map(function() {
return $(this).attr("name");
}).get();
console.log(getName);
});
id
should be unique in html. You should use class
attribute:
<p class="name" data-name="print">hey</p>
<p class="name" data-name="this">hey</p>
<button id="btn11">test11</button>
$("#btn11").click(function(){
$.each($(".name"), function(i, v) {
console.log($(v).data("name"))
})
});
Also, name
is not a property of <p>
tag. See Element.name
You should not use dupicate IDs in HTML, still you want to use the the same here is the code which works as you expected
$("#btn11").click(function () {
$("p[id='name']").each(function (e) {
alert($(this).attr("name"));
});
});
DEMO HERE
id should be unique. not remended to use duplicate id's in the html document. still if you want continue with your old code.
you can also do like this
document.querySelectorAll('p[id=name]')[0]
Extremely bad practice.
Two separate elements should NOT contain the same ID nor name. Apply a class name and iterate (using an each or map) through the class name. There are many ways to do this (I already see some solid examples here). Then, make use the data attribute to store unique data per each element.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744938337a4602163.html
评论列表(0条)