How to get <a> innerText based on class name? - javascript

Say I have: <a class="helloh" id="helloh">return this value</a>
Basically I want to get the innerText of <a> tag based on class name.
The problem is when I try: alert(document.getElementsByClassName("helloh").innerText); it return undefined but when I try: alert(document.getElementById("helloh").innerText); it return me they actual value that I want.

use document.getElementsByClassName("helloh")[0].innerText instead of document.getElementsByClassName("helloh").innerText.
When using getElementsByClassName, you will get array of elements instead of single array unlike getElementById.

A new syntax version is document.querySelector() which will return the first matching element. It saves you having to do getElementsByClassName('name')[0]
From the following:
<a class="helloh" id="helloh">get by ID</a>
<a class="helloh2" id="helloh2">get by Class</a>
You can use:
// by ID
console.log(document.querySelector('#helloh').innerText)
// by Class
console.log(document.querySelector('.helloh2').innerText)
If you want multiple elements, you can use document.querySelectorAll():
<a class="helloh" id="helloh">get by ID</a>
<a class="helloh" id="helloh2">get by Class</a>
// get both by Class
console.log(document.querySelectorAll('.helloh'))
Notice the # and .
You specify classes with ., IDs by #, and omit both to search by block elements .
For example, document.querySelectorAll('div') will return all divs on the page.
You can also use multiple at the same time:
document.querySelectorAll('div .helloh #helloh2')

var a = document.getElementsByClassName("helloh")[0].textContent;
alert(a);
<a class="helloh" id="helloh">return this value</a>

Related

JS querySelectorAll function does not select intended css class

I try to select the careerPoints class with JavaScript, but when I type querySelectorAll I get "undefined". Besides, when I type querySelector I can get only the first element on the loop.
This is my code:
<body>
<h1>Hi</h1>
{%for x in range(0, 16)%}
<ul>
<li scope="row"><p>Name:</p> {{dataName[x]['firstName']}} {{dataName[x]['lastName']}}</li>
<li class="points"><p>Career Points</p><p class="careerPoints">{{dataName[x]['careerPoints']}}</p> </li>
<li class="numbers"><img width="100px" src="{{dataName[x]['headShotUrl']}}" alt="{{dataName[x]['firstName']}} {{dataName[x]['lastName']}}"></li>
<li class="numbers"><p>Height</p> {{dataName[x]['height']}}</li>
</ul>
{%endfor%}
<script>
var elements = document.querySelectorAll("careerPoints").text;
console.log(elements);
</script>
</body>
It should be querySelectorAll(".careerPoints").
querySelectorAll uses CSS selectors. In this case . selects the class. # would select the id, for example.
The other issue is this (I've added the . for convenience).
var elements = document.querySelectorAll(".careerPoints").text;
querySelectorAll returns a nodelist, so you can't just select text from it because there is no text property on a nodelist (note: there is no text property at all). You need to iterate over the nodelist and then select the textContent (or innerText which behaves a little differently) from each element. Here's a small example using forEach to log the text to the console.
const elements = document.querySelectorAll(".careerPoints");
elements.forEach(element => console.log(element.textContent));

how to get element id on click without any inline function call in javascript?

I need to change the element's class clicked upon to 'selected' This is a part of my html file:
<div class="side-nav white-nav" id="sidenavblade">
<ul>
<span id="trigger-1" class="menu-trigger"><li>
<a href="<?php echo URL::to('/')."/initiatives" ?>" class="">
<span id="trigger-1" class="menu-trigger" >INITIATIVES <i class="icon initiatives"></i>
</a>
</li></span>....
there are 10 more 'li' in the class 'side-nav'
I need to change the class of icon to 'selected' for the 'a' element clicked upon.
My js :
var select=false;
t=document.getElementById('sidenavblade');
e=t.getElementsByTagName('a');
$(e).click(function(){
if(select==true){
$('.selected').removeClass('selected');
}
$(this).getElementsByClassName('icon ').addClass('selected');
select=true;
});
But, 'this' comes out to be 'undefined'. How can I change my function to get the element clicked upon, without calling the function for each element separately.
You're mixing jQuery and native DOM calls for no apparent reason. This just won't work:
$(this).getElementsByClassName('icon ').addClass('selected');
However, it's easy with the library:
$(this).find('.icon').addClass('selected');
The DOM API returns a NodeList, and you can't use it like a jQuery object.
Similarly:
e=t.getElementsByTagName('a');
$(e)
might work, but I'm not sure; certainly it's simpler to just write
$('a').click(function() {
// ...

how to remove a pattern in big string that holds specific value using javascript?

i got a big javascript variable that holds around 100 <li> </li> sets of data. i want to filter these sets if for example some words found in them(remove that set if a word from array found in them). These words i set them in array(items=["mango","apple","pen"];)
could any one tell me how this can be done?
example of <li></li> sets:
<li>
<img src="./mango.jpg" width="180" height="148"
alt="mango season" class="png">
<div class="thumbnail_label">ok</div>
<div class="details">
<div class="title">
<a href=
"/mango/"> mango</a>
<span class="season">2</span>
</div>
<ul class="subject">
<li>read</li>
</ul>
<ul class="sub-info">
<li class="location">Europe</li>
<li class="price">2</li>
</ul>
</div>
</li>
I'm going to list the methodology / functions I'd use to do this - not going to go into the exact code since I get the sense this is a generic example.
Change the string to a set of DOM elements so you can use DOM functions on them - maybe make a <div id="dom_set" display="none"> and do an innerHTML of your big string
Create an array of the list items: var elementArray = document.getElementById('dom_set').querySelector(li);, so elementArray[0] is the first li, etc.
Iterate over the array: var testString = elementArray[0].outerHTML; - note that outerHTML is not 100% cross-browser compatible so you'd need to prototype it (can Google how to prototype outerHTML)
Within this iteration, iterate over your array of words to check for, and check them. So it'd be if(testString.indexOf(badWordArray[j] > -1)) Note that indexOf doesn't work in IE8 so you need to prototype that too.
In your 'if' statement, if the bad word is in there then you can remove the node
After cycling through all the nodes, you can convert back to a string by var cleanString = document.getElementById('dom_set').innerHTML;
There's obviously a lot of the actual code for you to fill in but this is probably a cleaner approach that's less likely to mess up than trying to do a whole heap of elaborate string manipulation.
Assuming that the values you want ("mango", "apple", "pen") are the text children of the "a" element inside of a "div" element with class "title" inside of a "div" element with class "details", and assuming you can use jQuery:
function itemsFromHtmlFragment(htmlFragment) {
var selector = 'div[class=details] div[class=title] a';
return $(selector, htmlFragment).map(function(idx, el) {
return $(el).text().trim();
});
}
var bigVariable = '<li> <img ... ';
itemsFromHtmlFragment(bigVariable); // => ["mango"]

changing class of a tag which is not using id

Apologies for asking more or less the same question again. I just noticed that i am using another name instead of 'id'.
<li emage="toto" class="jstree-leaf">
<ins class="jstree-icon2"> </ins>
<a class=""><ins class="jstree-icon2"> </ins>Story B</a>
</li>
I need to change the class of the <ins> tags for a specific <li> where emage value is 'toto'.
If i was using 'id' instead of 'emage', i would have used the following:
$("#toto ins").attr("class","className");
But since am not using id, how can i change the class of the inner <ins> tags.
Your suggestions are much appreciated
Try the following
$('li[emage="toto"] ins').attr('class', 'className');
This will update the class of all ins tags inside the li with the attribute emage that has the value "toto"
Use the attribute selector:
$("li[emage='toto'] ins").attr("class","className");

jQuery problem, jQuery takes over all links on page

<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
$("#results").load( "jquery-routing.php", { pageNo: $(this).text(), sortBy: $("#sortBy").val()} );
return false;
});
});
</script>
<div id="results"> </div>
1
2
that code works fine, only problem that after I run it all my a href links stop to work! The links become jquery ajax calls.. why?
You're $("a") selector matches all <a ...> tags, you need to change it to something more specific:
$("a#someid")
$("a.someclass")
$("div#somecontainer a")
To target specific links, use the id or class tag on your anchor tags.
E.g.
<a class="link1" href=""></a>
<a id="link2" href-""></a>
Do note that id tags are unique within a page and can only be used once.
Reference those links in jQuery using:
$('a.link1').click(function() {}
$('#link2').click(function() {}
or you can combine both:
$('a.link1, #link2').click(function() {}
What you need to do is assign an id or class tag to the link that will call the ajax request. E.g. <a class="ajax" href="">ajax</a> and referencing it with $('a.ajax').click(function () {}
Your setting the onclick event of all anchor tags on the page. Try only selecting the link that you want instead of the more general $("a")
Your selector $("a") indicates all the hiperlink in your page.
You may need to give a specific id to the hiperlink where you want your ajax call to work and then change the selector based on that.
ex:
<a id= "my-link" href="" >ddd</a>
$("a#my-link").click()

Categories