使用JavaScript按标题选择元素并从浏览器调整? [英] Select an element by title with JavaScript and tweak from the browser?

查看:82
本文介绍了使用JavaScript按标题选择元素并从浏览器调整?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按标题修改元素,如

I need to modify an element by title, as in

javascript: (function () {
  document.body.innerHTML += `<style>* {
    background:% 20#000 % 20!important;
    color:% 20#0f0 % 20!important;
    outline:% 20solid % 20#f00 % 201px % 20!important;
  } </style > `;
})();

所以我想修改那些代码,这样当我运行它时(我把它放在我的按钮上)书签栏以方便访问)它改变了文档上某个元素的位置。

So I want to modify that code so when I run it (I have it in a button on my bookmarks bar for easier access) it changes the position of a certain element on the document.

我选择这个元素的唯一方法是它的 title 属性,所以我需要找到一种方法,用 javascript 按标题选择元素,然后对其样式应用更改,与此相同Ghost CSS技巧。

The only way I could select this element is by its title attribute, so I need to find a way to select an element by title with javascript and then apply a change to its style, same as that "Ghost CSS" trick.

推荐答案

CSS选择器

使用选择器表示法查找节点通过它的属性

Use the selector notation for finding a node by it's attribute

[title="element title attribute value"]






使用 JavaScript


Using JavaScript

与CSS中的选择器相同,但您可以使用节点 ttps://developer.mozilla.org/en-US/docs/Web/API/document.querySelectorrel =noreferrer> document.querySelector ,或者如果期望多个节点,则 NodeList 通过 document.querySelectorAll

Same selector as in CSS, but you can get the Node using document.querySelector, or if expecting multiple Nodes, a NodeList via document.querySelectorAll

var node = document.querySelector('[title="element title attribute value"]');






当你执行时。 innerHTML ,您正在重新解析您调用它的节点中的所有 HTML ,这可能会破坏网页的各个部分。您应该使用 DOM方法来创建节点。例如。


When you do .innerHTML, you are causing a re-parse of all HTML in the node you've called it on and this can literally destroy sections of web pages. You should use DOM methods for creating nodes, instead. e.g.

var style = document.createElement('style');
style.appendChild(document.createTextNode('div {border: 1px solid red}'));
document.body.appendChild(style);






JavaScript 转换为bookmarklet就像


Converting JavaScript into a bookmarklet is as simple as

bookmarklet = 'javascript:'
    + encodeURIComponent('(function () {' + code + '}())')
    + ';';

这是一个小提琴 ,您只需粘贴代码

Here is a fiddle where you can just paste in code

这篇关于使用JavaScript按标题选择元素并从浏览器调整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆