JS querySelectorAll function does not select intended css class - javascript

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));

Related

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

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>

How do I filter <li> under a<ul> having a particular id?

<ul class="apple" id="A">
<li>
<li>
.....
......
......
</ul>
<ul class="apple" id="B">
<li>
<li>
.....
......
......
</ul>
In the above code I get the ul having id B using jQuery selector.
$(selector).find('ul.apple #B') This does not seem to work.
I want to display all the li under the ul having class=apple & id ="B" . The above code is in FTL ( freemarker) & I am trying to trigger the id written in freemarker from the js code.
Thanks :)
Id's should be unique in a document. You never need to include any other selector but the id itself $('#B'). No need for .find or anything - there's only one on the page anyway.
If you want a reference to the li tags under #B, here are two ways:
//get a reference to the list
var $B = $('#B');
//get children (which are lis)
var $lis = $B.children();
or just get the lis directly:
var $lis = $('#B li');
Normall you only need to specify the id, as it's unique in the page, so a selector like this would work:
#B li
If you still need to specify the element and class, for example if you are using the same CSS for several pages, you would specify them without spaces between:
ul.apple#b li
In the HTML 4.01 specification, it is specified that element IDs must be unique.
That said, you can just query by the id via:
$('#A');
select UI by id and class name:
$('B .apple')

How to call non-form elements within a form tag

given the following markup:
<form>
<p>Example text.</p>
<label>My Label</label>
<input type="text">
</form>
. . . how would I get the p element from the form HTMLCollection. For example:
<script>
var myForm = document.getElementsbyTagName('form')[0];
console.log(myForm[0]);
</script>
This code returns the input element, and not the paragraph. so, how would I grab the paragraph?
You can use getElementsByTagName on the form as well:
// Get the first paragraph element, if any
var p = myForm.getElementsByTagName('p')[0];
On modern browsers, you can use querySelector and querySelectorAll to use just about any CSS expression:
// Get the first paragraph element, if any
var p = myForm.querySelector('p');
querySelector finds the first matching element. querySelectorAll returns a static list of matching elements.
myForm.childNodes[1] will return <p>Example text.</p>:
var myForm = document.getElementsByTagName('form')[0];
console.log(myForm.childNodes[1]);
jsFiddle example

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"]

get method isn't returning results

I'm trying to simply reproduce what is on the jquery site for the .get method:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
</ul>
<script type="text/javascript">
alert($('li').get());
</script>
</body>
</html>
It should return
[<li id="foo">, <li id="bar">]
But all I get is [object HTMLLIElement],[object HTMLLIElement]
Does anybody know what I might be doing wrong here?
Everything is alright:
The .get() method grants us access to the DOM nodes underlying each
jQuery object.
Get returns the DOM elements hold by the jQuery variable.
And when you output DomElements they become the form "HTMLLIElement".
But that's what .get does! It will retrieve the HTML DOM elements matched by the selector. If you want the jQuery objects, you should use just $('li').
Simple, select the ul element and display it's content with the html function:
alert($('ul').html());
html docs:
Description: Get the HTML contents of the first element in the set of matched elements.
You're not necessarily doing anything wrong.
What you're getting is the actual result of calling toString (which alert will do for you) on an array with 2 <li> DOM objects in it:
[object HTMLLIElement],[object HTMLLIElement]
However, what's mentioned in the API Documents isn't a string representation of the array, but is meant as a description of the array's current state in memory:
[<li id="foo">, <li id="bar">]
It was meant just as a shorter way of saying something like this:
The result is an array with 2 DOM objects that represent the <li id="foo"> and <li id="bar"> elements, respectively.
Now, if you actually want to get the markup in the alert, you'll have to get the outer HTML of the elements. Then try:
alert($('li').map(function () { return $(this).outerHTML(); }).get());
Example: http://jsfiddle.net/cmpwM/

Categories