Javascript function innerHTML not styled correctly - javascript

I'm trying to update some HTML using javascript in a webapp that uses JQuery mobile.
For some reason, I can not use the innerHTML attribute to create a JQuery Mobile button.
For example:
document.getElementById('someDiv').innerHTML = document.getElementById('someDiv').innerHTML + '<p><em>' + var1 + '</em>:<br />' + var2+'</p>';
works and gets styled correctly but:
document.getElementById('someDiv').innerHTML = document.getElementById('someDiv').innerHTML + '' + var1 + '';
does not. I should say that the someDiv is enclosed within a <div data-role="controlgroup"> if that would make any difference. Also, there are other buttons on the page that work fine.
Why doesn't this work and how can I make it work?
EDIT: I am compiling this into a native app using PhoneGap if that makes any difference...

You need to trigger the pageCreate event so that jQuery Mobile knows to re-style the element that you just added.
$("#someDiv").trigger("create")

When adding elements that have special functionality, it is important to re-run the initialisation of said functionality.
For this purpose, I like to define a dom_mods() function that does exactly that. So, whenever I add content to the page, I simply call dom_mods() and all my special features are run or updated.

It looks like you're trying to append an element to the div.
var div = document.getElementById('someDiv'),
anchor = document.createElement('a');
anchor.setAttribute('href', '#');
anchor.addEventListener('click', appendButton, false);
anchor.setAttribute('data-role', 'button');
anchor.innerHTML = var1;
div.appendChild(anchor);
Let me know if you have any questions.

Related

How to dynamically add data from a span tag into a href tag

I think this may have a simple answer that I'm missing. The following tag inserts a TV show name into any page on my website:
<span class="show-title"></span>
what I'm trying to do is incorporate that data dynamically into a HREF URL link.
So, let's say on the page I'm on:
produced the result: GOTHAM.
I'd like to then use that data to create this url:
https://en.wikipedia.org/wiki/GOTHAM_(TV_series)
So I'm trying stuff like:
</span>_(TV_series)"> Link
or
Link
nothing working - any help would be awesome. Thanks!
You could do something like this:
In HTML
<a class="wikipedia-link">Link</a>
And your JavaScript function:
setLink(showTitle) {
var link = document.getElementsByClassName("wikipedia-link");
link.setAttribute("href", "https://en.wikipedia.org/wiki/" + showTitle + "_(TV_series)");
}
The html you use is wrong. span shouldn't be inside tag a. No tag inside another.
If your result is in javascript variable, you can set the url using jquery.
$('a').attr('href', "https://en.wikipedia.org/wiki/" + result + "_(TV_series)");
result variable is your desired result.
Although there's better ways of going about doing this, I'm going to answer the question in the context in which you presented it:
First, give the url link a class or ID so you can easily select it with JavaScript to change the href value later. Also, don't try to nest the span tag anywhere inside the a tag. Leave it outside.
<span class="show-title">GOTHAM</span>
Link
Next, in a JavaScript file or a <script> tag, define your variables:
var showTitle, showWikipediaLink, linkElement
Then, assign value to your newly defined variables
linkElement = document.querySelector('.show-wikipedia-link');
showTitle = document.querySelector('.show-title').innerText;
showWikipediaLink = 'https://en.wikipedia.org/wiki/' + showTitle + '_(TV_series)';
Finally, use JavaScript to update the href value of the link element to the show's Wikipedia link:
linkElement.href = showWikipediaLink;

the reason why Conflict between plugin and javascript function occured

Few days ago I had to write code quickly and added the bad code below.
<td class="note_box_con" onclick="getElementsByTagName('a')[0].click();">
After then, when I tried to use Text editor plugin written by Javascript, I found
Text editor plugin and the function of DOM collide into each other
Now I know what was the problem and solve it. But I cannot understand what kind of risk getElementsByTagName('a')[0].click(); has.
In my incomplete view, that code is just addEventlistener function().....
what kind of risk onclick="getElementsByTagName('a')[0].click();" has?
In my understanding, its a bad practice to do it this way. I would rather suggest you to use to fetch using classname or id.
If you are using some resource that adds anchor tags to your page, this will break your logic.
Following is a simulation:
var count = 0;
function addAnchor(){
var div = document.getElementById("content");
var str = "<a href='#'>" + count++ + "</a>";
div.innerHTML = str + div.innerHTML;
}
document.getElementsByTagName("a")[0].addEventListener("click", function(){
console.log(this.innerHTML);
return false;
})
<div id="content">
Test
</div>
<button onclick="addAnchor()">Add Link</button>
<a onclick="document.getElementsByTagName('a')[0].click()"> test </a>
Also, if there is a change in DOM structure, your code will not work properly. Best use a proper selector that uniquely identifies the element.

jQuery Chosen plugin query

I am using chosen plugin for a multiple select and I want to dynamically display all the selected options somewhere in the page.
I am able to show them, however, I also want to remove them if someone deselects/removes them. This is what I am struggling with.
My code till now looks like
$(".chosen-select").chosen({max_selected_options: 5}).change(function() {
var bStr = "#home-summary-right";
var htmlContent = $("#home-summary-right").html();
$(".search-choice").find("span").each(function() {
$(bStr).html("" + htmlContent);
toAppend = '<span>' + $(this).text() + '</span>';
$(bStr).append(toAppend);
});
});
Okay
Otherwise, is there any way to disable removing of elements once they are select in the multiple select? There is that cross, to which I can do display none, but I still don't know how can i disable the backspace from removing the elements.
Okay, I fixed it.
I used setTimeout in combination with bunch of other things.
The problem was after change, the inner html would return the same content as before... So I called an event after pretty much everything was done. Works super smooth!

.innerHTML vs. createElement() | setAttribute() vs. Direct*

I was told this was not "proper", I did not worry about it until I started getting a run-time error in IE9. Here is the code I need converted to use object properties.
Why is innerHTML not considered best practice?
var c=document.createElement('div');
c.innerHTML= '<a name="a1" class="b" href="' + d[2].value + '">' + d[1].value + '</a>';
It's strange that you're putting an A element inside an A element but the below should work.
var c=document.createElement('a');
c.name = "a1";
c.className = "b";
c.href = d[2].value;
c.appendChild(document.createTextNode(d[1].value));
This assumes that d[1].value is not known to be well formed HTML from a trusted source so it is likely to be more robust against XSS than the innerHTML code.
innerHTML is perfectly fine, you are just not using it correctly.
innerHTML targets the content of a tag. meaning what's between <a> and </a>
you need to set your d[2].value with setAttribute and only d[1].value with innerHTML
this should be fine (untested)
var c=document.createElement('a');
c.setAttribute("href",d[2].value);
c.setAttribute("name","a1");
c.setAttribute("class","b");
c.innerHTML = d[1].value;
check these references and examples for setAttribute (method) and innerHTML (property)
It looks like you are creating an anchor - by using document.createElement('a') - and then creating another anchor within it. So, basically your HTML is going to look like this:
<a>
Click Here
</a>
This is not right. This is the reason why using innerHTML for anchors is not good. I think you should do it as follows:
c.setAttribute('class', 'signature');
c.setAttribute('href', 'xyz');
and so on.
You can also set the href and other attributes directly on the anchor using javascript. See http://www.w3schools.com/jsref/dom_obj_anchor.asp (Anchor object properties).

.html() and .append() without jQuery

Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>

Categories

Resources