Do you create it like this: $('<div />') or $('<div></div>')
Is that how you create an element? Thanks.
Either way works just fine. Just don't forget to insert in the dom - you can use appendTo(selector).
var $my_elem = $("<div/>").appendTo(document.body);
var $my_elem = $("<div class='abc'></div>").appendTo(document.body);
Then you have $my_elem represending the inserted element.
Looking at the jQuery source code, it looks like anything matching the regular expression /^<(\w+)\s*\/?>(?:<\/\1>)?$/ will be interpreted as a "single tag" and passed directly to document.createElement (assuming no context is specified). Therefore, at least in the current implementation, there's no difference (behavior or performance) between the various formats.
$('YOUR SELECTOR').append('<div />');
The <div /> will create a <div></div>
You can include classes, id's and other attributes, jQuery should figure it out and rap it up.
I included use of the append function because you are probably going to want to insert it somewhere. There is a number of similar functions you could use instead.
Related
I'm trying to develop a script that will take user submitted HTML, loop through it to identify matching tags, make adjustments to those matched tags, and then spit out the resulting HTML as plain text that the user can copy. The end goal here is to replace all href's in a submission and replace them with different URL's.
So for example, this:
Link A
<a data-track="false" href="http://example.com/">Link B</a>
Link C
Becomes this:
Link A
<a data-track="false" href="http://example.com/">Link B</a>
Link C
My first thought was to take the submitted HTML from the <textarea> field and put it in a variable. At this point the HTML becomes a string and I was going to loop through it with a regex to find matching tags. My issue was that I needed to find all <a> tags that did NOT include the attribute data-track="false". And as far as I can tell that's impossible with regex since each link isn't going to be on its own line.
My second thought was to loop through it using jQuery where I could use something like this:
$("a:not([data-tracking='false'])");
But I can't use jQuery like this on a string, right? It needs to be in the DOM.
I'm unsure of the best way to go about doing this. Maybe another language would prove helpful, but other than HTML and CSS, javascript and jQuery are the only ones I'm experienced with.
Any and all help would be greatly appreciated.
I think your question is similar to
Convert String to XML Document in JavaScript
The answer is that you can wrap it in a jQuery object. Then use jQuery's normal DOM manipulation methods on it.
var myhtml = $($('#main-input').val());
myhtml.find('a').each(function () {
alert($(this).text());
});
if it's a top level element you need to use filter instead of find.
You can create a jQuery object from html strings outside of the DOM and maniuplate it just the same as if it was in the DOM.
Simple example:
var html='<div><p>ABC</p></div>';
alert( $(html).find('p').text() ); // alerts "ABC"
Or
var $div= $('<div>').append(html).find('p').after('<p>DEF</p>');
var newHtml= $div.html();
Will return
<div>
<p>ABC</p>
<p>DEF</p>
</div>
Conclusion, I would loop through a jQuery object created from your html and do what you need using jQuery methods
I know how to do the opposite. Getting a certain DOMElement for a jQuery element is easy. (Use the get() method)
But how can you get a jQuery element for a specific DOMElement?
Unfortunately this DOMElement does not have any attributes like class or id so constructing a selector is not really an option.
Lets say I have this html:
<div class="edit">Abcd<b><i><u>asdasd</u>adasda</i></b>sdfsdf<br>asd</div>
I am in the u-DomElement. How can I get this as a jQuery element?
Is there a smart way to do this?
EDIT:
I wanted to know if there is a gerneral way to do this. Not specific to the code shown above.
Like:
DomElement.toJQuery()
Is there anything like that? I am aware that this might not be possible.
Getting a jQuery object for a DOM object is as simple as jQuery(dom_node) (or $(dom_node)). See http://api.jquery.com/jQuery/
This is commonly used in event handlers, which are given the DOM node as this, so that you will often see $(this)
If you want to get just the Element use the below code. if you wanted to get the HTML of any element you might want to add the .html() tag to either of the examples
var myVar = $('.edit u');
or
var myVar = $(".edit").find("u");
Are you looking for this?
$(".edit").find("u");
hope this is what you are looking for,
$(DomElement)
you want a only 1 specific dom element i suggest you find a way to add an id to that element.
but to get an u element inside a edit class:
$('.edit u');
$('.edit').find('u');
I see a lot of reference for replacing text between tags or replacing tags identified with an ID, but my task is quite different in that I need to replace part of the tag itself. For example, I want to change...
<body etc>
So that it becomes...
<body somestring etc>
The change needs to be performed in the browser using JavaScript, ie: after a CMS (like Wordpress) has finished with it.
Looks like you need to add new attribute to DOM element:
document.getElementsByTagName("html")[0].setAttribute("id", "something");
document['getElementsByTagName']('html')[0]['setAttribute']('attr', 'value');
If you are using jQuery you can accomplish this with a line like the following:
$("html").attr({foo:"bar", baz:"bing"});
If you run a wordpress website you might already be using jquery. With JQuery this is something easy
$('html').attr('id', 'bob');
//just for testing
alert($('html').attr('id'));
If you are setting the value of standard attributes, just use DOM properties:
document.getElementsByTagName("html")[0].id = 'foo';
or more simply:
document.documentElement.id = 'foo';
It's not a good idea to set non–standard attributes or properties, use data-* attributes instead.
I have a div with id #test that contains lots of html, including some youtube-embeds etc.
Somewhere in this div there is this text: "[test]"
I need to replace that text with "(works!)".
The normal way of doing this would of course be:
document.getElementById("test").innerHTML = document.getElementById("test").replace("[test]","(works!)");
But the problem is that if i do that the youtube-embeds will reload, which is not acceptable.
Is there a way to do this?
You will have to target the specific elements rather than the parent block. Since the DOM is changing the videos are repainted to the DOM.
Maybe TextNode (textContent) will help you, MSDN documentation IE9, other browsers also should support it
Change your page so that
[test]
becomes
<span id="replace-me">[test]</span>
now use the following js to find and change it
document.getElementById('replace-me').text = '(works!)';
If you need to change more than one place, then use a class instead of an id and use document.getElementsByClassName and iterate over the returned elements and change them one by one.
Alternatively, you can use jQuery and do it even simpler like this:
$('#replace-me').text('(works!)');
Now for this single replacement using jQuery is probably overkill, but if you need to change multiple places (by class name), jQuery would definitely come in handy :)
First post on stackoverflow. Hope everything is right!
I'm thinking of attaching an ID value to the HTML element itself via JavaScript, instead of using the HTML id attribute.
For instance, say that JavaScript variable htmlElement is a div. So htmlElement.cssName would tell us its CSS class.
Now, how about doing
htmlElement.idProperty = "someValue"
in JavaScript instead of doing <div id="someValue">? Then I can use the idProperty in say event handlers.
this.idProperty
That simple!
Is there something wrong in doing so?
EDIT: Thanks for yor answers! Very helpful and instructive. I wish I could check green on all of them!
no, you can do it the way you like it, if you are dynamically creating this item you should use this method, if you are doing this inside html I recommend you to just put the name of the id in html too.
However a small note. Use element.id instead of idProperty.
element.id = 'my-id';
You can use the createAttribute method to add an id to the element like this:
id = document.createAttribute('id');
id.value = "someValue";
htmlElement.setAttributeNode(id);
What you're doing there is adding a runtime property (in your case, called idProperty) to an HTMLElement object instance. You can get away with doing that in your JavaScript code (the Prototype library does it all the time). Makes me uncomfortable, but it does work on all major browsers.
If you want to be able to specify these in HTML markup as well, though, I'd use attributes instead. You can create attributes with any names you want, although to be careful I'd use names like data-xyz (e.g., use a data- prefix) as that's the HTML5 standard way of using your own attributes. Then you use getAttribute to get the value and setAttribute to set/update the value.