07.jQuery changing and manipulating HTML elements and attributes
jQuery changing and manipulating HTML elements and attributes
Get Content - text(),
html(), and val()
Three
simple, but useful, jQuery methods for DOM manipulation are:
1.
text()
-
Sets or returns the text content of selected elements - $("#test").text();
2. html()
- Sets or returns
the content of selected elements (including HTML markup) -$("#test").html();
3.
val()
-
Sets or returns the value of form fields - $("#test").val()
Get Attributes
$("#One").attr("href"); - <p><a
href="https://www.abc.com" id="One">W3Schools.com</a></p>
Set Content - text(),
html(), and val()
$("#test1").text("Hello
world!");
$("#test2").html("<b>Hello
world!</b>");
$("#test3").val("Dolly
Duck");
Set Attributes - attr()
$("#One").attr({
"href" : "https://www.abc.com/jquery/",
"title" : "Abc jQuery Tutorial"
});
Add Elements
We
will look at four jQuery methods that are used to add new content:
- append() -
Inserts content at the end of the selected elements
- prepend() - Inserts content at the beginning of the selected elements
- after() -
Inserts content after the selected elements
- before() -
Inserts content before the selected elements
append() - $("p").append("Some
appended text.");
prepend() - $("p").prepend("Some
prepended text.");
after() - $("img").after("Some
text after");
before() - $("img").before("Some
text before");
var txt1
= "<b>I </b>"; // Create element with HTML
var txt2 = $("<i></i>").text("love
"); // Create with jQuery
var txt3 =
document.createElement("b"); // Create with DOM
txt3.innerHTML = "jQuery!";
$("img").after(txt1, txt2,
txt3); // Insert new elements after <img>
Remove Elements
- remove() -
Removes the selected element (and its child elements)
- empty() -
Removes the child elements from the selected element
$("#div1").remove();
$("#div1").empty();
$("p").remove(".test");
$("p").remove(".test,
.demo");
jQuery Manipulating CSS
jQuery
has several methods for CSS manipulation. We will look at the following
methods:
addClass()
- Adds one or more classes to the selected elementsremoveClass()
- Removes one or more classes from the selected elementstoggleClass()
- Toggles between adding/removing classes from the selected elementscss()
- Sets or returns the style attribute
.important {
font-weight: bold;
font-size: xx-large;
}
.blue {
color: blue;
}
$("#div1").addClass("important
blue");
$("h1, h2,
p").removeClass("blue");
$("h1, h2,
p").toggleClass("blue");
jQuery css() Method
The css()
method sets or
returns one or more style properties for the selected elements.\
$("p").css({"background-color": "yellow", "font-size": "200%"});
Comments
Post a Comment