baptx
baptx

Reputation: 3896

Avoid textNode creation after new line?

If I manually write those following lines in an HTML file:

<div>
<input type="button" value="Button 1">
<input type="button" value="Button 2">
</div>

A text node will be created for each new line.

I wanted to understand the useCapture argument of addEventListener method. I choosed to access DOM elements using childNodes property of my div element but I will have to ignore textNodes between elements. This isn't really practical:

document.getElementsByTagName("div")[0].addEventListener("click", function(){alert(1);}, true);

document.getElementsByTagName("div")[0].childNodes[1].addEventListener("click", function(){alert(2);}, false);

document.getElementsByTagName("div")[0].childNodes[3].addEventListener("click", function(){alert(3);}, false);

Here you see that I have to ignore childNodes[0] and childNodes[2] in order to select my 2 input tags.

Is there a way to bypass textNodes creation without writing all HTML code just on one line and without using Javascript createElement?

Is it possible to write HTML code without creating textNodes when going to new line?

Upvotes: 4

Views: 586

Answers (3)

Alnitak
Alnitak

Reputation: 339816

Firstly, don't repeat yourself ! You're repeating the same DOM query over and over.

Try this:

var div = document.getElementsByTagName("div")[0];
div.addEventListener("click", function(){alert(1);}, true);

var buttons = div.getElementsByTagName("button");  
buttons[0].addEventListener("click", function(){alert(2);}, false);
buttons[1].addEventListener("click", function(){alert(2);}, false);

calling getElementsByTagName to get the buttons trivially skips the text nodes - problem solved!

Upvotes: 1

Eraden
Eraden

Reputation: 2858

Sorry. Only possibility is generate HTML code using programming language such as PHP, RUBY and add something like this.

<input type="button" value="Button 1"><%-
%><input type="button" value="Button 2">

But I guess it's not answer you want hear.

Upvotes: 1

gdoron
gdoron

Reputation: 150253

Is it possible to write HTML code without creating textNodes when going to new line?

Nope.

Unless you parse the HTML file before sending it to the client, which I guess that solution isn't what you're after...

Upvotes: 1

Related Questions