Skip to content Skip to sidebar Skip to footer

I Am Getting Empty Values For Sports-title And Third

i am new to js. can you tell me why I am getting empty values for sports-title and third. since we have one div with content in it. sports-title---->{'0':{}} third---->{} pr

Solution 1:

When you call an object in the Document Object Model (DOM) using any of the GetElement selectors, it returns an object that can be considered that HTML element. This object includes much more than just the text included in the HTML element. In order to access the text of that element, you want to use the .textContent property.

In addition, an HTML class can potentially be assigned to several elements and therefore GetElementsByClassName returns an array so you would have to do the following, for example:

console.log("sports-title---->" + JSON.stringify(sportsTitle[0].textContent));

You can find a brief introduction to the DOM on the W3Schools Website. https://www.w3schools.com/js/js_htmldom.asp If you follow along it gives an overview of different aspects of the DOM including elements.

Solution 2:

Maybe this would be helpful As you see sportsTitle[0].textContent returns full heading and 0 is the index thus you get "0" when you stringify (serialize) sportsTitle. Why 0? Because you have one <h1> element . See this fiddle http://jsfiddle.net/cqj6g7f0/3/ I added second h1 and see the console.log and you get two indexes 0 and 1

if you want to get a word from element so get substring use substr() method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

One way is to change <h1> class attr to id and do sportsTitle.textContent; and use substr() on this string or 2nd way is to remain class attr and do sportsTitle[0].textContent; and substr() on this string

The 2nd is the better way

Post a Comment for "I Am Getting Empty Values For Sports-title And Third"