Created span in javascript is showing as [object HTMLSpanElement] in webpage - javascript

I created a span tag in javascript and using .innerHTML i'm trying to append it into another tag. but in webpage it is showing as [object HTMLSpanElement].
var text = "Accessor Properties Example";
var enteredText = 'Prop';
var data = text.split(enteredText);
var pTag = document.getElementById('ab');
var newSpan = document.createElement('span');
newSpan.setAttribute('class','highlight');
newSpan.innerHTML=enteredText;
console.log(newSpan)
var plainText = data[0]+newSpan+data[1];
pTag.innerHTML = plainText;
.highlight {color:#1a0dab;font-weight:bold}
<p id="ab"></p>

You're trying to insert an object reference into a string. You can get the HTML that represents the span and add the 3 pieces of information together before setting the innerHTML of your target.
var text = "Accessor Properties Example";
var enteredText = 'Prop';
var data = text.split(enteredText);
var pTag = document.getElementById('ab');
var newSpan = document.createElement('span');
newSpan.setAttribute('class','highlight');
newSpan.innerHTML=enteredText;
console.log(newSpan)
var plainText = data[0]+ newSpan.outerHTML +data[1]; // <- Change made here
pTag.innerHTML = plainText;
.highlight {color:#1a0dab;font-weight:bold}
<p id="ab"></p>

That's because you are concatenating strings with a DOM element, which is coerced into a string too.
Instead, you should use appendChild:
pTag.innerHTML = ''; // Remove existing contents
pTag.appendChild(document.createTextNode(data[0]));
pTag.appendChild(newSpan);
pTag.appendChild(document.createTextNode(data[1]));
var text = "Accessor Properties Example",
enteredText = 'Prop',
data = text.split(enteredText),
pTag = document.getElementById('ab'),
newSpan = document.createElement('span');
newSpan.className = 'highlight';
newSpan.textContent = enteredText;
pTag.innerHTML = '';
pTag.appendChild(document.createTextNode(data[0]));
pTag.appendChild(newSpan);
pTag.appendChild(document.createTextNode(data[1]));
.highlight {color:#1a0dab;font-weight:bold}
<p id="ab"></p>

Related

After concatenating html elements the result variable return 0

here is my code it return 0 when i call result variable i want to add elements in html without DOM, means i want to re-create this whole html in JS using this code.
var div = document.createElement("div");
div.setAttribute("id", "old");
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "new");
var p = document.createElement("p");
p.setAttribute("id", "paragraph")
var domDiv = document.getElementById("old");
var domNewDiv = document.getElementById("new");
var domP = document.getElementById("paragraph");
var result = domDiv + domNewDiv + domP;
result;
Code in console
document.getElementById returns a Javascript Object. You cannot simply concatenate objects. But you can concatenate the html content of those objects for example:
var result = domDiv.innerHTML + domNewDiv.innerHTML + domP.innerHTML;

Appending htmlfragment to an element

I am loading json data and displaying them on site inside div.
I decided to store the data inside an htmlfragment using
var docFragment = new DocumentFragment();
function createFullList(){
var aside = document.getElementsByClassName("one")[0];
for( x in obj ){
createInfoElement( docFragment , obj[x].general , obj[x].job );
}
var div = document.createElement("div");
div.appendChild(docFragment);
aside.innerHTML += div;
}
crateInfoElement just creates div and append it to docFragment.
What is troublling me is when i want to append an documentFragment into its supposed holder ( aside variable ).
It does not display all divs inside it instead of it just
[object HTMLDivElement]
I do not have much experience with fragments , but using example from MDN
var ul = document.getElementsByTagName("ul")[0]; // assuming it exists
var docfrag = document.createDocumentFragment();
var browserList = ["Internet Explorer", "Mozilla Firefox", "Safari", "Chrome", "Opera"];
browserList.forEach(function(e) {
var li = document.createElement("li");
li.textContent = e;
docfrag.appendChild(li);
});
ul.appendChild(docfrag);
it does display ul and li elements inside it not just
[object HTMLDivElement]
as in my case. What is causing this behavior?
createInfoElement looks like this
function createInfoElement( parent , name , job ){
var div = document.createElement("div");
div.setAttribute("class","left_info");
var p = document.createElement("p");
p.setAttribute("class","name");
p.innerHTML = name.firstName + " " + name.lasName;
var p_two = document.createElement("p");
p_two.setAttribute("class","job");
p_two.innerHTML = job.title;
div.appendChild(p);
div.appendChild(p_two);
parent.appendChild(div);
}

How to add an element to another one(instead of using selector)

I found in Document that I can create an element and add another one to it like:
var sel = document.createElement("select");
var opt1 = document.createElement("option");
var opt2 = document.createElement("option");
opt1.value = "1";
opt1.text = "Option: Value 1";
opt2.value = "2";
opt2.text = "Option: Value 2";
sel.add(opt1, null);
sel.add(opt2, null);
But when I tried to apply it to practice, this method doesn't work, newUser was not added to newDiv successfully:
function createOnEle(imgSrc, user, extract) {
var newDiv = document.createElement("div");
var newUser = document.createElement("span");
newUser.textContent = user;
newDiv.add(newUser);
}
It seems that add method doesn't work for div and span, if this is true, how to achieve it? Otherwise, Where did I wrong?
.add is a method of select-element which is used to add an option-element to it.
Refer HTMLSelectElement.add()
Use .appendChild()
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
function createOnEle(user) {
var newDiv = document.createElement("div");
var newUser = document.createElement("span");
newUser.textContent = user;
newDiv.appendChild(newUser);
document.body.appendChild(newDiv);
}
createOnEle('RogB :)')
function createOnEle(imgSrc, user, extract) {
var newDiv = document.createElement("div");
var newUser = document.createElement("span");
newUser.textContent = user;
newDiv.innerHTML=newUser;
}
This should also work as per your requirement .

Setting ID input (DOM) issue

I wonder why this won't work. I'm trying to set an ID on two input-field, so I can grab it, then use it in a function. I can create the elements and then set an ID, but my task requires me to do it this way (School project).
var div = document.getElementById('div');
var p = document.createElement('p');
var butt = document.createElement('input');
var inputOne = document.createElement('input');
var inputTwo = document.createElement('input');
div.appendChild(inputOne);
div.appendChild(inputTwo);
inputOne.SetAttribute="type","text";
inputOne.placeholder="Something";
inputTwo.SetAttribute="type","number";
inputTwo.placeholder="SomethingElese";
butt.type="button";
butt.value="clickMe!";
div.appendChild(butt);
butt.onclick=func();
inputOne.SetAttribute="id","MyID";
function func(){
var text = document.getElementById('MyID').value;
alert(text);
}
Because of the errors.
var div = document.getElementById('div');
var p = document.createElement('p');
var butt = document.createElement('input'); // really? I can think of better names
var inputOne = document.createElement('input');
var inputTwo = document.createElement('input');
div.appendChild(inputOne);
div.appendChild(inputTwo);
inputOne.setAttribute("type","text"); // call this as a function with a lowercase "setAttribute"
inputOne.placeholder="Something";
inputTwo.setAttribute("type","number"); // this too
inputTwo.placeholder="SomethingElese";
butt.type="button";
butt.value="clickMe!";
div.appendChild(butt);
butt.onclick=func; // pass the function by reference, not calling it
inputOne.setAttribute("id","MyID"); // again
I got it working now. Here's the result code - Thanks!
var div = document.getElementById('myDiv');
var butt= document.createElement('input');
var inputOne = document.createElement('input');
var inputTwo = document.createElement('input');
div.appendChild(inputOne);
div.appendChild(inputTwo);
inputOne.setAttribute("type","text");
inputOne.placeholder="Something";
inputTwo.setAttribute("type","number");
inputTwo.placeholder="SomethingElse";
butt.type="button";
butt.value="ClickMe";
div.appendChild(butt);
butt.onclick=func;
inputOne.setAttribute("id","MyID");
function func(){
var text = document.getElementById('MyID').value;
alert(text);
}

JS - text value of tag - when tag is string

How can I get text value of a tag when tag is stored as string?
var value = "<div>teeext</div>";
tag can be anything, its attributes may contain ">" string as well, regexp can be dangerous - also text value itself can be another tag.
You can make a dummy element:
var value = "<div>teeext</div>";
var div = document.createElement('div');
div.innerHTML = value;
var text = div.innerText || div.textContent;
Using just javascript:
var div = document.createElement('div');
var value = "<div>teeext</div>";
div.innerHTML = value;
var element = div.firstChild
console.log(element.innerHTML); //this the stuff in the tag
Using jquery:
$(value).html();
I guess that you're trying to strip tags.. In that case you can do it like this:
originalString = "<div>teeext</div>";
var value = originalString.replace(/(<([^>]+)>)/ig,"");
Test it out. If there are any exceptions which you need to handle, then just comment here and I'll try to help you further.
Edit for multiple tags:
originalString = "<div>teeext</div>";
outputString = originalString;
while (outputString.indexOf(/(<([^>]+)>)/ig) !== -1){
outputString = outputString.replace(/(<([^>]+)>)/ig,"");
}
value = outputString;
Haven't tested it, but you get the point ;)
Does this help as a starter?
function getText(tagString) {
var firstOpenTag = tagString.indexOf(">"),
lastCloseTag = tagString.lastIndexOf("</"),
substrLength;
if (firstOpenTag == -1 || lastCloseTag == -1) {
return tagString;
}
substrLength = (tagString.length - firstOpenTag) - (tagString.length - lastCloseTag) - 1;
return tagString.substr(firstOpenTag + 1, substrLength);
}
var value = "<div>teeext</div>";
console.log(getText(value));
var moreTags = "<div><ul><li>Text</li></ul></div>",
returnValue = moreTags,
prevReturnValue = "";
while (returnValue !== prevReturnValue) {
prevReturnValue = returnValue;
returnValue = getText(returnValue);
}
console.log(returnValue);

Categories