Directly adding text into innerHTML without using innerText - javascript

Is it possible to add string inside innerHTML without having to use innerText?
like this:
var sentence="<b>hello there</b>";
document.querySelector(".container").innerHTML='<span class="thing"></span>';
document.querySelector(".thing").innerText=sentence;
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="container"></div>
</body>
</html>
but without having to use innerText,
Maybe the code would look something like this:
var sentence="<b>hello there</b>";
document.querySelector(".container").innerHTML='<span class="thing">'+raw(sentence)+'</span>';

I don't see anything seriously wrong with your current approach. If you want to avoid the repetition of creating an element with a particular class and then have to select it again right after you append it, you can consider creating an element instead of an HTML string:
var sentence="<b>hello there</b>";
document.querySelector(".container")
.appendChild(document.createElement('span'))
.textContent = sentence;
<div class="container"></div>

Related

How to use javascript to find and replace a word split in a few tags?

I want to use javascript to find and replace a word which has been split in a few tags.
For example, the html code:
<html>
<body>
<div id="page-container">
This is an apple.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
</div>
</body>
</html>
And the it looks like below in the web browser:
This is an apple.
apple.
I use this javascript to find and replace the word "apple":
var a = document.getElementById('page-container').innerHTML;
a=a.replace(/apple/g,'pear');
document.getElementById('page-container').innerText=a;
But the result in the web browser is very bad, and all the tags could not work:
This is an pear.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
It seems the replace function worked for the first row but cannot recognize the word split in the tags. This is an example, the whole content could be much more complex with more tags like , , not only ... Is there a way to replace only text but keep the original html tag format?
var a = document.getElementById('page-container').textContent;
a = a.replace(/apple/g, 'pear');
var a=a.split('.');
document.getElementById('page-container').innerHTML = `${a[0]}.<br/><span> ${a[1]}
<span>`;
That is because you have nested elements, so when you set innerHTML of the parent div, it treats inner div as text and print it out , try to replace this :
document.getElementById('page-container').innerText=a;
with this :
document.getElementById("page-container").firstChild.innerHTML = a;
So, you target only your first child which is parent div.
Live example:
https://jsbin.com/hujurageya/edit?html,js,output

Select element in Jquery selector by class name and convert it back to Jquery object

I don't understand why when i looking for how to get an element in list of element selected by class name like in traditional JS, I've always seen complicated answers .
document.getElementsByClassName('anyclass')[1]
so, i have found out myself that i cant do that (may be its the wrong approach)
$('.anyclass')[1]
but i get a DOM element! so logically i tried
$('.anyclass')[1][0]
and it doesnt work 'TypeError: $(...)[0][0] is undefined'
Anyone can explain why ? thank you!
I think you need .eq(index)
var secondElement = $('.anyClass').eq(1); //jQuery object
var domElement = secondElement[0]; //DOM element
console.log(secondElement, domElement)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='anyClass'>1</div>
<div class='anyClass'>2</div>
var elm = document.createElement("div");
var jelm = $(elm); //convert to jQuery Element
var htmlElm = jelm[0]; //convert to HTML Element
The :first pseudo-class is equivalent to :eq( 0 ). It could also be written as :lt( 1 ). While this matches only a single element, :first-child can match more than one: One for each parent.
here
$('.anyclass:first)
Quick example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$($(".t")[1]).css("background-color", "yellow");
});
</script>
</head>
<body>
<p class=t>This 1.</p>
<p class=t>This 2.</p>
<p class=t>This 3.</p>
</body>
</html>
'
$('.anyclass')[0].attr("src"); you can use like this .
after your comment:
$(".anyclass")[1] is a DOM element not a jquery object. Simply wrap it as jquery $($("td")[1]).width()

Any way to get nearby html nodes different from current node's tag name in NodeJS?

Let's say I have the following html code..
<html>
<head></head>
<body>
<div>
<input type ="text">
<img src = "pic.jpg">
Home
</div>
</body>
</html>
And I want to look at the nodes around an element that's on the same level. For example, from the above html code, is it possible to do something like...
$("input").returnNodesOnSameLevel()
and it can return a list of nodes which here would contain [< input...>, < a...> ] ?
I'm using NodeJS's request module to grab the page source and then using Cheerio to do my parsing. The sibling() only returns nodes of the same tag name which makes sense. If there's a better module or another way to do this, please let me know.
Thank you.
If $("input").siblings() doesn't work, you could try: $("input").parent().children()

How to display JavaScript variables in a HTML page without document.write

I am trying to display some JavaScript variable on my HTML page.
I was first using document.write() but it use to overwrite the current page when the function was called.
After searching around, the general consensus was that document.write() isn't liked very much. What are the other options?
I found a page suggesting using .innerHTML but that was written in 2005.
A jsFiddle illustrating my problem http://jsfiddle.net/xHk5g/
Element.innerHTML is pretty much the way to go. Here are a few ways to use it:
HTML
<div class="results"></div>
JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div>. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
Full example. Click run snippet to try it out.
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);
// JQuery example
var $jqName = $('.name');
var $jqValue = $('.jqValue');
$jqName.on('input', function(event){
$jqValue.html($jqName.val());
});
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Setting HTML content example</title>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
</body>
</html>
You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:
<div id="MyEdit">
This text will change
</div>
You can use javascript to change the content like so...
document.getElementById("MyEdit").innerHTML = "My new text!";​
Here is a working example
You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.
For example, with JQuery, you could do this to acheive the same result...
$("#MyEdit").html("My new text!");
Here is a working example of the JQuery version
Based on this example you provided in your post. The following JQuery would work for you:
var x = "hello wolrd";
$("p").html(x);
Here is the working version
Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.
there are different ways of doing this.
one way would be to write a script retrieving a command.
like so:
var name="kieran";
document.write=(name);
or we could use the default JavaScript way to print it.
var name="kieran";
document.getElementById("output").innerHTML=name;
and the html code would be:
<p id="output"></p>
i hope this helped :)
You could use jquery to get hold of the html element that you want to load the value with.
Say for instance if your page looks something like this,
<div id="FirstDiv">
<div id="SecondDiv">
...
</div>
</div>
And if your javascript (I hope) looks something as simple as this,
function somefunction(){
var somevalue = "Data to be inserted";
$("#SecondDiv").text(somevalue);
}
I hope this is what you were looking for.
If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
​var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);​​​​​​
innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.
document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";
Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as
uploadElement.style.width = "100%";
hi here is a simple example: <div id="test">content</div> and
var test = 5;
document.getElementById('test').innerHTML = test;
and you can test it here : http://jsfiddle.net/SLbKX/
Add an element to your page (such as a div) and write to that div.
HTML:
<html>
<header>
<title>Page Title</title>
</header>
<body>
<div id="myDiv"></div>
</body>
</html>
jQuery:
$('#myDiv').text('hello world!');
javascript:
document.getElementById('myDiv').innerHTML = 'hello world!';
Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"<br>
$('.output').html(value);
CSHTML:
<div class="output"></div>

body.innerHTML before/after nth-child

Is it possible to add something with innerHTML before/after the nth child of <body>?
e.g.:
<html>
<head></head>
<body>
<div id="first">First</div>
<div id="second">Second<div id="second_sub"></div></div>
<div id="third">Third</div>
</body>
</html>
I can add at the beginning with body.innerHTML = html + body.innerHTML and at the end with body.innerHTML += html but how to add, for example, before the second <div>?
I don't want to use replace on <div id="second"> as the source changes and the insert should be done at random. Is there a solution with innerHTML or do I need to switch to Dom Nodes? Would be slow in old browsers :(
You are probably looking for the insertBefore method. It will insert a child before the given element. Alternatively there's the appendChild method which will always push elements on the beginning of the given element.
Examples:
<body>
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
Let's assume we're inserting a new element stored in the var newElem:
document.insertBefore(newElem, document.getElementById("elem2")) will give:
<body>
<span id="elem1">Hello</span>
<!-- New element here! -->
<span id="elem2">World</span>
</body>
document.appendChild(newElem) will give:
<body>
<!-- New element here! -->
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
I'm using this by now (Thanks to ajax333221):
e = document.createElement('div');
e.innerHTML = '<div>... huge content with several sub elements ...</div>';
document.body.insertBefore(e, document.body.childNodes[2]);
This is a combination of both techniques. With this I'm able to use the fast .innerHTML without extremely blowing up the code with createElement(), setAttribute(), etc.
Other solutions are welcome.

Categories

Resources