最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML Label name instead of ID? - Stack Overflow

programmeradmin3浏览0评论

I am making website where I am created a lot of labels that are assigned in output as here

Use fiddle link at the end of the post

<!-- lets say that I want to make a kind of board to show some game clans or... whatever -->

<label class='team' name='ally'>Madcowz</label><BR>
<label class='team' name='ally'>Fluffy Unicorns</label><BR>
<label class='team' name='enemy'>Blue bastards</label><BR><BR>

<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>

<!-- The problem is that the NAME tag does not exist for label in this case: -->
<!-- I can't use ID because ID should be unique values -->
<script>
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
    document.getElementById('printSomeOutputHere').innerHTML += teams[i].name + ": " + teams[i].textContent;
    document.getElementById('printSomeOutputHere').innerHTML += "<BR>";
}
</script>

I am making website where I am created a lot of labels that are assigned in output as here

Use fiddle link at the end of the post

<!-- lets say that I want to make a kind of board to show some game clans or... whatever -->

<label class='team' name='ally'>Madcowz</label><BR>
<label class='team' name='ally'>Fluffy Unicorns</label><BR>
<label class='team' name='enemy'>Blue bastards</label><BR><BR>

<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>

<!-- The problem is that the NAME tag does not exist for label in this case: -->
<!-- I can't use ID because ID should be unique values -->
<script>
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
    document.getElementById('printSomeOutputHere').innerHTML += teams[i].name + ": " + teams[i].textContent;
    document.getElementById('printSomeOutputHere').innerHTML += "<BR>";
}
</script>

Fiddle: http://jsfiddle/cusnj74g/

name attribute is undefined, so how can I mark these labels with same name if I can't use (I can, but I should not) ID

Share Improve this question edited Jan 19, 2015 at 18:20 T.J. Crowder 1.1m200 gold badges2k silver badges2k bronze badges asked Jan 19, 2015 at 18:11 Bartłomiej SobieszekBartłomiej Sobieszek 2,8102 gold badges28 silver badges44 bronze badges 12
  • 2 use a data attribute? data-name? – Shan Robertson Commented Jan 19, 2015 at 18:12
  • 1 are you wanting a jQuery solution or a plain javascript solution? – DA. Commented Jan 19, 2015 at 18:16
  • 1 "Use fiddle link at the end of the post" If you don't want people to use the Stack Snippet in your question, make the code in the question just a code block (not a Stack Snippet). But really, it's better to use a Stack Snippet than a fiddle now that SO has them. – T.J. Crowder Commented Jan 19, 2015 at 18:19
  • 2 teams[i].getAttribute("name") – 1252748 Commented Jan 19, 2015 at 18:20
  • 1 @Mouser: "you are allowed to make custom attributes" Only if they start with data-. – T.J. Crowder Commented Jan 19, 2015 at 18:25
 |  Show 7 more ments

4 Answers 4

Reset to default 5

A couple of points:

  1. You seem to know that name is not a valid attribute for label elements. So don't use it, use data-name instead.

  2. You're using label elements incorrectly. There are two ways you use label: A) By putting the input, select, or textarea it relates to inside it (<label><input type="checkbox"> No spam please</label>), or by using the for attribute to associate it with one of those elements elsewhere in the document (<label for="no-spam-please">No spam please</label>...<input id="no-spam-please" type="checkbox">). Having a label with no control in it and no for is fairly pointless; just use a span.

  3. You're using jQuery in one place, but not in others. I suggest that if you're going to have a library on your page, it's best to get full use out of it. In this case, to access the attribute, you'd use $(teams[i]).attr("name") or better, $(teams[i]).attr("data-name") if you're using a data-* attribute (see #1 above). (Some may tell you to use .data to access the attribute; don't, that's not what it's for. But you might consider looking at what it's for and whether that helps you.)

  4. .innerHTML += "content" is an anti-pattern. It makes the browser loop through all elements within the element you're doing it to to build a string, then append the string on the right with it, then parse the result, and delete all existing elements within the element and replace them with the parsed result. Instead, consider .insertAdjacentHTML("beforeend", "content")

  5. You don't declare i anywhere, which means your code falls prey to The Horror of Implicit Globals. Declare i, or use any of several other ways to loop that don't require an index counter.

  6. Your output will be fairly hard to read, remend breaking it up (perhaps a div for each team?).

  7. textContent is not reliable cross-browser, some browsers use innerText instead. (And there are differences in how whitespace is treated between them.) Since you're using jQuery, use text.

...but yes, the code would work if you used .getAttribute("name") rather than .name. Browsers make access to even invalid attributes available through getAttribute. They just don't necessarily create reflected properties for them.

Here's a version with the various ments above applied:

var output = $("#printSomeOutputHere");
$(".team").each(function() {
  var $this = $(this);
  output.append("<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>");
});
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>

<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

...or to avoid repeated appends we could use map and join:

$("#printSomeOutputHere").append(
  $(".team").map(function() {
    var $this = $(this);
    return "<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>";
  }).get().join("")
);
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>

<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

From https://developer.mozilla/en-US/docs/Web/API/Element.name:

[The name property] only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>.

Since you're using jQuery I would use something like:

for(var t in teams){
    $('#printSomeOutputHere').get(0).innerHTML += 
        teams[t].getAttribute("name") 
        + ": " 
        + teams[t].text() 
        + "<BR />";
}

Use getAttribute instead:

teams[i].getAttribute('name')

Why not use multiple classes:

<label class='team ally'>Madcowz</label><BR>
<label class='team ally'>Fluffy Unicorns</label><BR>
<label class='team enemy'>Blue bastards</label><BR><BR>

And the JS:

<script>
var outEl = document.getElementById('printSomeOutputHere');
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
    outEl.innerHTML +=
        (teams[i].hasClass('ally')? 'ally':'enemy') + ": " +
        teams[i].textContent;
}
</script>
发布评论

评论列表(0)

  1. 暂无评论