Want to point javascript to ID?

hi im new to javascrtipt and don´t know the terms so cant find out what to search for

i have code that truncate the text of my links
so <a href=“myfruitandvegetable.com”>Fruit and vegetables</a>
result without code Fruit and vegetables
and with code Fruit and…

here is code i found on the net.

<script type="text/javascript">
var oElement = document.getElementById("test");
$('a').text(function(index, oldText) {
  return oldText.length > 9 ? oldText.substring(0, 9) + '...' : oldText;
});
</script>

so far so good.
i also have other link on same page
<a href=“myhomepage.com”>Copyright 2012 myhomepage.com</a>
so when the script is on as you already has guessed.
the result would be Copyright…
what it should not do.

so i was thinking
what if i gave the 2 links some id like this
<a id=“truncateon” href=“myfruitandvegetable.com”>Fruit and vegetables</a>
<a “truncateoff” href=“myhomepage.com”>Copyright 2012 myhomepage.com</a>

so code only truncated link if it has the id=truncateon"
i think in the javascript line 2
$(‘a’).text(function(index, oldText) {
is the one that find the<a tag with the $(‘a’) code.
but dont know how or if its possible to add the id=“truncateon” to it.

hope it makes sense.
mu best regards dahlsvarehus

An ID must be unique on the page, so you cannot have two elements with the same ID.
Instead of an ID you could use a class, or perhaps data attribute. I don’t know much about using data attributes in selectors so we’ll go with a class


<a href="myfruitandvegetable.com" class="truncate">Fruit and vegetables</a>
<a href="myhomepage.com">Copyright 2012 myhomepage.com</a>


<script type="text/javascript">
$('a.truncate').text(function(index, oldText) {
  return oldText.length > 9 ? oldText.substring(0, 9) + '...' : oldText;
});
</script>

There’s no need to mark both the links to truncate and the links to not truncate. One is the inverse of the other.

thank you cranial-bore
Perfect!