How can I create a HTML-Element dynamically, do something with it and then it should be removed.
But it is important that it will be really deleted.
Here is my approach:
var newdiv = document.createElement('div');
newdiv.setAttribute('id','MyDiv');
$('#MyDiv').css({'width':'100px','height':'100px'});
$('#MyDiv').html('This is a test');
$('#MyDiv').remove(); // It should be work ?
// Is it possible to delete it as follows?
newdiv.remove();
As I mentioned, it is important to really delete the element, since the Function "createElement()" can often get invoked.
How can I test whether the new created HTML-Element is really removed?
I test as follows, whether the element is still existed, but I get always true!
alert( $('#MyDiv').length == 1);
Below are a two links, but they were not enough for, in order to solve my problem.
setting the id attribute of an input element dynamically
createElement and delete DOMElement
Thanks.
try this one maybe is what you want:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var div = document.createElement("div");
$(function(){
$("body").append( div);
$(div).css({'width':'100px','height':'100px','border':'solid 1px black'}).html('This is a test');
//$(div).remove();
});
</script>
</head>
<body>
</body>
</html>
dont forget to uncoment the //$(div).remove();
First of all, I see, you have an error in your code in this line:
newdiv.setAttribute('id','#MyDiv')
value of id attribute must not have '#' (the hash sign) - with your code element newdiv will have id like "#MyDiv" but this is not valid ID for jQuery, due to jQuery use this template for ID Selector (“#idName”)
You can dynamically delete the element with your way, but I guess previously you should to append it to another element on page using jQuery.append(you element/selector) method
If you can use jQuery you can try with the following:
$( "body" ).append( "<div id="MyDiv">This is a test</div>" ); // Create MyDiv div before </body> tag (you can use .prepend( ... ) to create it after <body>)
$("#MyDiv").css({'width':'100px','height':'100px'}); // Give some style to MyDiv
$("#MyDiv").remove(); // Delete MyDiv
Related
I am new in javascript.I am trying this below code to get href attribute.
Facebook
<script type="text/javascript">
function cheak()
{
var a= document.getElementsByTagName("a").getAttribute('href');
alert(a);
}
</script>
I know this is working by below code
document.getElementById("myid").getAttribute('href'); // if I use any id
But in tag I don't want to use any id or class. How can I get this attribute without using any id or class in a tag.
Preface: Below, I've answered the question of how to find an element without using an id or class, in the general case. But if you just want the element from within your cheak function, then Zain's answer is the correct way to do that (with minimal changes to your code; arguably more correct might be modern event hookup).
But in tag I don't want to use any id or class. How can I get this attribute without using any id or class in a tag.
You reach for the Swiss army knife of element selection: document.querySelector. With it, you can use any CSS selector that matches the element:
var href = document.querySelector("any selector here").getAttribute("href");
querySelector returns the first match in the document. (There's also querySelectorAll, which returns a list.) They're both supported in all modern browsers, and also IE8.
Since you have the full power of CSS selectors, you can use anything about the position of the element in the document to find it.
There's too little context in your question for a specific example, but for instance if it's the first a in the document:
var href = document.querySelector("a").getAttribute("href");
alert(href);
Facebook
Or using that onclick:
var href = document.querySelector("a[onclick='cheak()']").getAttribute("href");
alert(href);
Facebook
If you pass in this when calling the function. it will pass the element reference to your function and you can use it to get value of href:
Facebook
<!-- Note -----------------------------^^^^ -->
<script type="text/javascript">
function cheak(a) {
alert(a.href); // Gives you the fully-resolved URL
alert(a.getAttribute("href")); // Gives you the content of the `href` attribute (not fully-resolved)
}
</script>
the parameter data is the complete tag on which the function is called
Facebook
<script type="text/javascript">
function cheak(e)
{
e.preventDefault();
// var a= document.getElementsByTagName("a").getAttribute('href');
alert(e.target);
}
</script>
I dont know Javascript at all, so sorry for asking a question like this...
This is what I have:
$(document).ready(function(){$("#more0").click(function(){$("#update0").slideToggle("normal");});});
$(document).ready(function(){$("#more1").click(function(){$("#update1").slideToggle("normal");});});
$(document).ready(function(){$("#more2").click(function(){$("#update2").slideToggle("normal");});});
$(document).ready(function(){$("#more3").click(function(){$("#update3").slideToggle("normal");});});
$(document).ready(function(){$("#more4").click(function(){$("#update4").slideToggle("normal");});});
$(document).ready(function(){$("#more5").click(function(){$("#update5").slideToggle("normal");});});
$(document).ready(function(){$("#more6").click(function(){$("#update6").slideToggle("normal");});});
$(document).ready(function(){$("#more7").click(function(){$("#update7").slideToggle("normal");});});
$(document).ready(function(){$("#more8").click(function(){$("#update8").slideToggle("normal");});});
$(document).ready(function(){$("#more9").click(function(){$("#update9").slideToggle("normal");});});
$(document).ready(function(){$("#more10").click(function(){$("#update10").slideToggle("normal");});});
And So On.. Until #more30 and #update30...
So... Right now, my pages has 30 lines :)
Is there a way to do it less complicated?
Thanks!
Use attribute selector ^= . The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value.
$(document).ready(function(){
$("[id^='more']").click(function(){
$("#update" + $(this).attr('id').slice(4)).slideToggle("normal");
});
});
Try to use attribute starts with selector to select all the elements having id starts with more , then extract the numerical value from it using the regular expression and concatenate it with update to form the required element's id and proceed,
$(document).ready(function(){
$("[id^='more']").click(function(){
var index = $(this).attr('id').match(/\d+/)[0];
$("#update" + index).slideToggle("normal");
});
});
use attribute start with selector
$(document).ready(function(){
$("[id^='more']").click(function(){
$("[id^='update']").slideToggle("normal");
});
});
//select all elements that contain 'more' in their id attribute.
$('[id^=more]').click(function(){
//get the actual full id of the clicked element.
var thisId = $(this).attr("id");
//get the last 2 characters (the number) from the clicked elem id
var elemNo= thisId.substr(thisId.length-2);
//check if last two chars are actually a number
if(parseInt(elemNo))
{
var updateId = "#update"+elemNo;//combine the "#update" id name with number e.g.5
}
else
{
//if not, then take only the last char
elemNo= thisId.substr(thisId.length-1);
var updateId = "#update"+elemNo;
}
//now use the generate id for the slide element and apply toggle.
$(updateId).slideToggle("normal");
});
Well first of all, you could replace the multiple ready event handler registrations with just one, e.g
$(document).ready(
$("#more0").click(function(){$("#update0").slideToggle("normal");});
//...
);
Then, since your buttons/links has pretty much the same functionality, I would recommend merging these into a single click event handler registration as such:
$(document).ready(
$(".generic-js-hook-class").click(function(){
var toggleContainer = $(this).data('toggleContainer');
$(toggleContainer).slideToggle("normal");
});
);
The above solution uses HTML Data Attributes to store information on which element to toggle and requires you to change the corresponding HTML like so:
<div class=".generic-js-hook-class" data-toggle-container="#relatedContainer">Click me</div>
<div id="relatedContainer>Toggle me</div>
I would recommend you to use Custom Data Attributes (data-*). Here You can store which element to toggle in the data attributes which can be fetched and used latter.
JavaScript, In event-handler you can use .data() to fetch those values.
$(document).ready(function () {
$(".more").click(function () {
$($(this).data('slide')).slideToggle("normal");
});
});
HTML
<div class="more" data-slide="#update1">more1</div>
<div class="more" data-slide="#update2">more2</div>
<div id="update1">update1</div>
<div id="update2">update2</div>
DEMO
I want to strip all html tags from user input.
This code strip all html tags from #container, except anchor and img tags.
$("#container").find('*:not(a,img)').each(function() {
$(this).replaceWith(this.innerHTML);
});
I can't convert it to find input text .val();
$('#inputTxt').val().find('*:not(a,img)').each(function() {
$(this).replaceWith(this.innerHTML);
});
This code shows error :
$input.val().find() is not a function.
Can someone help me?
Updated POST
well, the example Mr antyrat gave was removing all contents inside any other tags, but I wanted content of them, just removing their tags. so I changed it like this and it's wokring.
var tmpElement = $( $( '#inputTxt' ).val() ); // create tmp HTML node
tmpElement.find('*:not(a,img)').each(function() {
$(this).replaceWith(this.innerHTML);
});
return tmpElement.html();
PROBLEM
above code works well with some inputs like these:
<div> Hello I am a link </div>
<a href="#" ></a><div>Hello<img src="url" /></div>
but when user types something like this:
<div><a <div ></div> href="#" ></a></div>
the output is : <a <div=""> href="#" >Another link</a>
This is the jsfiddle
This hapens because val() method returns input value, not the jQuery object, and this value doesn't have method find()
In your code:
$(this).replaceWith(this.innerHTML);
this is reference to jQuery element, not Node so you can't get innerHTML.
Also if inputTxt is input element you can't find any elements inside it as they are just plain text. You need to convert them to HTML at first, for example:
var tmpElement = $( $( '#inputTxt' ).val() ); // create tmp HTML node
tmpElement.find( '*:not(a,img)' ).remove(); // remove everything except <a> and <img> elements
$('#inputTxt').replaceWith( tmpElement ); // replace input to it's HTML content
But you need to be sure that input has correct HTML in it and has at least one root node. So better is to wrap your HTML into container, <div> for example:
var tmpElement = $( '<div>' + $( '#inputTxt' ).val() + '</div>' ); // create tmp HTML node
So the main problem you have is that you are trying to iterate over plain string like on elements.
See working demo on jsFiddle.
Update:
Event better is not to remove node w/ contents but just elements:
tmpElement.find( '*:not(a,img)' ).contents().unwrap(); // remove everything except <a> and <img> elements
updated jsFiddle
.val() returns a string, which is not a group of jquery objects, so .find() function doesn't work.
try:
$('#inputTxt').find('*:not(a,img)').each(function() {
$(this).replaceWith($(this).val());
});
http://www.frostjedi.com/terra/scripts/demo/jquery02.html
According to this link elements can be moved around by doing $('#container1').append($('#container2')). Unfortunately, it doesn't seem to be working for me. Any ideas?
See jsfiddle http://jsfiddle.net/Tu7Nc/1/
You must append not your div exactly, but your div's content(inner HTML) with Jquery's html() function.
HTML:
<div id="1">aaa</div>
<div id="2">bbb</div>
Jquery:
$("#1").append($("#2").html());
Result:
aaabbb
bbb
It is best not to use html().
I ran into some issues due to html interpreting the contents as a string instead of a DOM node.
Use contents instead and your other scripts should not break due to broken references.
I needed to nest the contents of a DIV into a child of itself, here is how I did it.
example:
<div id="xy">
<span>contents</span>
</div>
<script>
contents = $("#xy").contents(); //reference the contents of id xy
$("#xy").append('<div class="test-class" />'); //create div with class test-class inside id xy
$("#xy").find(">.test-class").append(contents); //find direct child of xy with class test-class and move contents to new div
</script>
[EDIT]
The previous example works but here is a cleaner and more efficient example:
<script>
var content = $("#xy").contents(); //find element
var wrapper = $('<div style="border: 1px solid #000;"/>'); //create wrapper element
content.after(wrapper); //insert wrapper after found element
wrapper.append(content); //move element into wrapper
</script>
To move contents of a div (id=container2) to another div (id=container1) with jquery.
$('#container2').contents().appendTo('#container1');
You can also do:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) el1.appendChild(el2);
or as one statement, but not nearly as robust:
document.getElementById('container1').appendChild(document.getElementById('container2'));
Edit
On reflection (several years later…) it seems the intention is to move the content of one div to another. So the following does that in plain JS:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) {
while (el2.firstChild) el1.appendChild(el2.firstChild);
}
// Remove el2 if required
el2.parentNode.removeChild(el2);
This has the benefit of retaining any dynamically added listeners on descendants of el2 that solutions using innerHTML will strip away.
$('#container1').append($('#container2').html())
Well, this one could be an alternative if you want to Append:
document.getElementById("div2").innerHTML=document.getElementById("div2").innerHTML+document.getElementById("div1").innerHTML
if you wanted to rewrite contents:
document.getElementById("div2").innerHTML=document.getElementById("div1").innerHTML
I suggest a general approach with a function and jQuery:
function MoveContent(destId, srcId) {
$('#' + destId).append($('#' + srcId).contents().detach());
}
Content of a detached source node is appended to a destination node with call:
MoveContent('dest','src');
The first parameter is an id of a new parent node (destination), the second is an id of an old parent node (source).
Please see an example at: http://jsfiddle.net/dukrjzne/3/
I wanted to ask how to change div content, but not using innerhtml.
DEMO: http://jsfiddle.net/Cb6ME/
// get the div
var div = document.getElementById('foo');
// remove child nodes while at least one exists
while( div.childNodes[0] ) {
div.removeChild( div.childNodes[0] );
}
// create a new span element
var span = document.createElement( 'span' );
// give it some text content
span.appendChild( document.createTextNode("I'm new!!!") );
// append the span to the original div
div.appendChild( span );
You can use nodeValue to access the value of a node, however the value of a div. In your example you might have the following HTML...
<div id="myLovelyDiv">This is the text that you want to change</div>
and this script...
var myDiv = getElementById("myLovelyDiv");
myDiv.childNodes[0].nodeValue = "The text has been changed.";
but I fail to see why you wouldn't use
myDiv.innerHTML = "The text has been changed properly.";
A DIV element is a generic block level (by default) element in HTML used as a structural container to hold one or more block or inline elements.
Depending on what it is you want to change you can either select the sub-node in question directly, loop over the childNodes property to find the desired sub-node or completely rewrite the contents as html using innerHTML (which you stated you didn't want to do).
If you want to add content you can create a new element and use the appendChild(child) method of the DIV element to add to it's contents.
Is that what you were looking for?
I know I'm late but .textContent can be replaced for .innerHTML (if you only want to change the text and not code HTML).