Using jQuery to get the content of div.class to replace content of title tag

419 views Asked by At

I need to work around a limitation on my company's platform where pages can only be rendered with the filename as the title. I don't want to change my file-names to have values like, "This page title with spaces, and maybe illegal characters", because I don't want my URLs to have a bunch %20's and illegal characters in them, so I've been trying to figure out how to use the contents of another section of the page over which I do have control - the breadcrumb - as the "title".

I've been trying to use jQuery's .get and .replaceWith to replace the contents of the title tag with the contents of span.ms-pagetitle, which contains the part I can edit, but I'm a jQuery noob, and just haven't been able to suss it out.

1

There are 1 answers

1
Alex Mcp On BEST ANSWER

This ought to do it:

$('title').text($('span.ms-pagetitle').text())

This should be run only once; usually inside a $(document).ready() function. The .ms-pagetitle element ought to have no children.

Two things are going on here:

$('span.ms-pagetitle').text() first selects any items matching span.ms-pagetitle. Hopefully there is just one, but it will grab them all. Use :first or another more specific selector to get the one you want. .text() will

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

...hence the idea to keep the span childless.

So that will result in a string of text.

$('title').text('string') will set the contents of a selected tag when passed a string (and get when used with no argument), so you are setting the selected title text as the contents of the <title> tag here.