0

I made a custom attribute to add a title to each links.

<a href="#" nameOf="The Flower" id="ex1"></a>
<a href="#" nameOf="The Tree" id="ex2"></a>

And here is the jQuery code

$('#ex1,#ex2').append('<span class="title">'+$(this).attr("nameOf")+'</span>');

But the link displays as undefined. How can I fix this.

raao
  • 17
  • 6
  • Custom attributes were used in the past, but since HTML5 with the support for the global `data-*` attributes, it is strongly recommended to use the `data-*` attributes instead. It is also recommended to use all small-letters for HTML tags and attributes. So change it to `data-nameof`. – Racil Hilan Feb 03 '18 at 05:33

4 Answers4

2

Iterate over the element tags & append to it

$('a').each(function(i, v) {
  $(this).append('<span class="title">' + $(this).attr("nameOf") + '</span>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" nameOf="The Flower" id="ex1"></a>
<a href="#" nameOf="The Tree" id="ex2"></a>
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can achieve the same as below using loop:

$('[nameOf]').each(function(){
    $(this).append('<span class="title">' + $(this).attr("nameOf") + '</span>')
});

but as per w3c rules you can not use nameOf attribute in a tag, So you can use use data-nameof instead.

Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
0

in HTML you can't create a custom attribute in camel case. if you want to add more words to your custom attr, you need to add a - symbol. so, for your case, do.

<a href="#" name-of="The Flower" id="ex1"></a>

later, for a search, I suggest you use the camel case.

$(element).attr('nameOf');
Kenry Sanchez
  • 1,703
  • 2
  • 18
  • 24
  • more info [link](https://stackoverflow.com/questions/36176474/camel-case-in-html-tag-attributes-and-jquery-doesnt-work-why) – Kenry Sanchez Feb 03 '18 at 04:55
0

the this in your example is window, it does not know that it is supposed to be a reference to a link. In order to use this, you would need to use a function inside of append() and return the string.

$('#ex1,#ex2').append( function() { return '<span class="title">'+$(this).attr("nameOf")+'</span>'});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" nameOf="The Flower" id="ex1"></a>
<a href="#" nameOf="The Tree" id="ex2"></a>

And if you do not want to use JavaScript at all and have the text show up in the link, there is always a CSS Solution.

a[nameOf]::before {
  content: attr(nameOf)
}
<a href="#" nameOf="The Flower" id="ex1"></a>
<a href="#" nameOf="The Tree" id="ex2"></a>
epascarello
  • 204,599
  • 20
  • 195
  • 236