jQuery is a popular JavaScript for creating dynamic web pages.
In this article, we’ll look at how to using jQuery in our web apps.
.width()
The .width()
method gets the current computed width for the first element in the set of matched elements or set the width of every matched element.
For example, we can write:
console.log($(window).width());
to log the width of the window.
To set the widths of the divs given the following HTML:
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
And CSS:
div {
width: 70px;
height: 50px;
float: left;
margin: 5px;
background: red;
cursor: pointer;
}
We can add click handlers to the divs and change the width inside by writing:
const modWidth = 50;
$("div").one("click", function() {
$(this).width(modWidth)
});
.wrap()
The .wrap()
method lets us wrap an element with a wrapper element.
For example, if we have:
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
Then we can wrap each div with the class inner
with a div with class new
by writing:
$(".inner").wrap("<div class='new'></div>");
.wrapAll()
The .wrapAll()
method lets us wrap an HTML structure around all elements in the set of matched elements.
For example, if we have:
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
Then we can wrap a div with class new
around all the divs with class inner
by writing:
$(".inner").wrapAll("<div class='new' />");
.wrapInner()
We can wrap an HTML structure around the content of each element in the set of matched elements with the wrapInner
method.
For example, if we have:
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
Then we can wrap the content of each div with class inner
with a div with class new
by writing:
$(".inner").wrapInner("<div class='new'></div>");
Conclusion
We can wrap elements with other elements with jQuery.
Also, we can get and set the width of the elements.