Using JavaScript to Access HTML Elements

Hi all! I am experimenting with manipulating DOM thorugh jQuery, but so far I think I need help.

GOAL: Change the headings displayed (refer to image) without changing any code in the HTML, but rather through changing JavaScript.

Here is the HTML:

<h1>Baby Seals</h1>
<h2 class="fact-header">Baby Seal Facts</h2>
<ul>
      <li class="first-fact">Baby seals are called pups.</li>
      <li>Pups are typically born in the spring or summer months.</li>
</ul>
<button>Learn more</button>

I then tried to access the HTML with JavaScript and manipulate it, so that the headings will change text as the button is clicked. When the latter part is done, the button itself will display a message from a browser.

Here is the JavaScript code, and the result when outputted to the console:

I am confused as to why the console is showing me this message instead of the actual text. When I click the button shown, nothing changes. If anyone could please help with this, I’d greatly appreciate it!

Hi there,

You’re getting this because you’re logging a jQuery wrapper object.
There’s in fact no need to log any of this to the console.

There’s a much simpler way to achieve what you’re trying to do.

$(document).ready(function() {
	$('button').on('click', function() {
		let subtitle = $('.fact-header');

		subtitle.text('Seal Your Baby Facts!');
	});
});
  1. Wait for the DOM to be ready for JS code to execute
  2. Select the element that will trigger an action when clicked
  3. Modify the text of the selected element you wish to change

You could even make it shorter

$(document).ready(function() {
	$('button').on('click', function() {
		$('.fact-header').text('Seal Your Baby Facts!');
	});
});

@ghostlovescore Thank you so much for your time in answering!! Your explanation makes a lot of sense.

I really appreciate the simple answer you give, however, as I am pretty new to this whole idea of accessing elements, there are still some things I don’t understand…

For instance, what is the purpose of $(document)?

Could you break down the first line? Also, what exactly do you mean when you say “a jQuery wrapper object”?

Greatly appreciate the help! :+1:

The best place to understand the purpose of this line is the official jQuery documentation:
https://learn.jquery.com/using-jquery-core/document-ready/

But we’re basically waiting for the page (Document Object Model) to be fully loaded and ready to start executing JavaScript code. So all your jQuery scripts should be wrapped in there.


Consider the following:

$(document).ready(function() {
	$('button').on('click', function() {
		let subtitle = $('.fact-header');

		console.log(subtitle);
	});
});

The console.log will give the following output in the browser’s console:

Object { 0: h2.fact-header, length: 1, prevObject: {…} }

Which can be expanded to show everything the object contains:

Object details
0: h2.fact-header
accessKey: ""
accessKeyLabel: ""
align: ""
assignedSlot: null
attributes: NamedNodeMap [ class="fact-header" ]
childElementCount: 0
childNodes: NodeList [ #text ]
children: HTMLCollection { length: 0 }
classList: DOMTokenList [ "fact-header" ]
className: "fact-header"
clientHeight: 29
clientLeft: 0
clientTop: 0
clientWidth: 1904
contentEditable: "inherit"
contextMenu: null
dataset: DOMStringMap(0)
dir: ""
draggable: false
firstChild: #text "Baby Seal Facts"
firstElementChild: null
hidden: false
id: ""
innerHTML: "Baby Seal Facts"
innerText: "Baby Seal Facts"
isConnected: true
isContentEditable: false
lang: ""
lastChild: #text "Baby Seal Facts"
lastElementChild: null
localName: "h2"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: <ul>​​nextSibling: #text " "
nodeName: "H2"
nodeType: 1
nodeValue: null
nonce: ""
offsetHeight: 29
offsetLeft: 8
offsetParent: <body>
offsetTop: 81
offsetWidth: 1904

… and many more!


So, you have an Object ( $('.fact-header') ) and some properties associated with this object. Let’s take the innerHTML property as an example.

Say you wanted the text to turn red when the button is clicked. You could insert some HTML if you wanted to achieve this.

N.B: In jQuery, the innerHTML property has been “simplified” to html().

Here’s the code to turn “Baby Seal Facts” to red:

$(document).ready(function() {
	$('button').on('click', function() {
		let subtitle = $('.fact-header');

        subtitle.html('<p style="color:red">' + subtitle.text() + '</p>');
	});
});

And there you go. In your HTML, what was previously

<h2 class="fact-header">Baby Seal Facts</h2>

Became

<h2 class="fact-header">
  <p style="color:red">Baby Seal Facts</p>
</h2>

​However,

We might not want to insert some unneeded paragraph (<p></p>) inside of the <h2> element. It’s redundant, probably not best practice, and there’s a much simpler way as well to change colors!

We know CSS is responsible for styling HTML pages and changing colors, right? So why don’t we simply make use of the css() method offered by jQuery?

$(document).ready(function() {
	$('button').on('click', function() {
		let subtitle = $('.fact-header');

		subtitle.css('color', 'red');
	});
});

Exact same result (visually), but the code is a bit cleaner.

From: <h2 class="fact-header">Baby Seal Facts</h2>
To: <h2 class="fact-header" style="color: red;">Baby Seal Facts</h2>

That’s already better! We haven’t injected any redundant elements, just modified the <h2> tag directly.


Could we make it even cleaner you say? Absolutely.

jQuery file:

$(document).ready(function() {
	$('button').on('click', function() {
		let subtitle = $('.fact-header');

		subtitle.addClass('red');
	});
});

CSS file:

.red {
  color: red
}

HTML result:

<h2 class="fact-header red">Baby Seal Facts</h2>

That’s right. Our jQuery code only modified the class attribute of our H2 element. It just added a red class, that is separated from our HTML and jQuery, located in our CSS file.

And, of course, exact same result visually. But our code stays clean.


All this to say that an Object contains a lot of properties that can be useful when we wish to modify our elements, inject new ones, etc. As you progress through your coding journey, you’ll be faced with new challenges depending on your ideas, and the sort of interactivity that you want to implement. Knowing about some of these properties and jQuery methods (such as css() and addClass()) can be useful!

Hope this helps and answers your questions! :slight_smile:

@ghostlovescore This explanation is really helpful!

I appreciate your time in writing such a detailed response. A lot of the things you mentioned are fairly new to me, but I grasp the idea you are trying to get at!

I will look over your response for the next few days for everything to sink in ahaha- that is to say, thank you so much!!

1 Like