I do not know anything about Jquery and would really appreciate some help or direction.
I am looking to insert all tags inside a tag into a singular tag for accessibility purposes.
The website in question is built inside a CMS(Sitefinity 14.2) where all HTML is inside a tag. Refer to below screenshots. I need to exclude all scripts and only have the tags between the Header and Footer tag inserted in the main tag.
Currently it looks like this:
<head></head>
<body>
<script>
<script>
<header>
<div>
<div>
<div>
<footer>
<script>
<script>
</body>
Whereas i am aiming for it to look like this:
<head></head>
<body>
<script>
<script>
<header>
<main>
<div>
<div>
<div>
</main>
<footer>
<script>
<script>
</body>
Below is a screenshot of the HTML.
Thank you in advance for any help or suggestions!
CodePudding user response:
$('div').wrapAll('<main>')
would do it:
$('div').wrapAll('<main>')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header></header>
<div></div>
<div></div>
<div></div>
<footer></footer>
Doc: https://api.jquery.com/wrapall/
CodePudding user response:
$('div:not(header *,footer *)').wrapAll('<main>')
header {
height: 100px;
background-color: yellow
}
footer {
height: 100px;
background-color: green
}
main {
height: 150px;
background-color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<div>
<h2>Header is not included in main, it's yellow</h2>
</div>
</header>
<div>Main Div 1, Main is blue</div>
<div>Main Div 2, Main is blue</div>
<div>Main Div 3, Main is blue</div>
<footer><div>
<h2>Header is not included in main, it's green</h2>
</div></footer>
Explanation
Additional to @j08691, if you want to only include divs that are not already wrapped by or , use the CSS selector :not()
combine with jQuery. Basic about :not()
W3School.
Since you have to Select div
that are not (!) children/descendants of header
or footer
and W3School only gives you a little basic about this, I'd like to explain a little bit further.
/* Select elements that are
not paragraphs */
:not(p) { /* ... */ }
/* Select paragraphs that
don't have the class "fancy" */
p:not(.fancy) { /* ... */ }
/* Select elements that are
not p or span */
:not(p):not(span) { /* ... */ }
/* Select elements that are
not p or span */
:not(p, span) { /* ... */ }
Dive deeper into the Specification of CSS Selector, you'll see that it's possible to select elements that are not (!) children/descendants of other elements using the universal selector (*). And that gives you the result div:not(header *,footer *)